package com.example.isoftservice.service.aop;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.example.isoftservice.mapper.MessageMapper;
import com.example.isoftservice.mapper.UserMapper;
import com.example.isoftservice.pojos.Logs;
import com.example.isoftservice.pojos.Message;
import com.example.isoftservice.pojos.User;
import com.example.isoftservice.service.LogsService;
import com.example.isoftservice.util.JwtUtils;
import com.example.isoftservice.util.logs.HoneyLogs;
import com.example.isoftservice.util.logs.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogsAspect {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private LogsService logsService;

//    @Resource
//    private LogsService logsService;
//
//    @Resource
//    private UserMapper userMapper;
//    @AfterReturning(pointcut = "@annotation(honeyLogs)", returning = "jsonResult")
//    public void recordLog(JoinPoint joinPoint, HoneyLogs honeyLogs, Object jsonResult) {
//        // 获取当前登录的用户的信息
//        String loginUser = (String) SecurityUtils.getSubject().getPrincipal();
//        if (loginUser == null) { // 用户未登录的情况下  loginUser是null  是null的话我们就要从参数里面获取操作人信息
//            // 登录、注册
//            Object[] args = joinPoint.getArgs();
////            if (ArrayUtil.isNotEmpty(args)) {
////                if (args[0] instanceof User) {
////                    loginUser = (User) args[0];
////                }
////            }
//        }
//        if (loginUser == null) {
//            log.error("记录日志信息报错，未获取到当前操作用户信息");
//            return;
//        }
//        // 获取HttpServletRequest对象
//        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//        HttpServletRequest request = servletRequestAttributes.getRequest();
//
//        // 获取到请求的ip
//        String ip = IpUtils.getIpAddr(request);
//        Logs logs = Logs.builder()
//                .operation(honeyLogs.operation())
//                .type(honeyLogs.type().getValue())
//                .ip(ip)
//                .user(loginUser)
//                .name(userMapper.login(loginUser).getRoleId().toString())
////                .user(loginUser.getUsername())
//                .time(DateUtil.now())
//                .build();
//
//        ThreadUtil.execAsync(() -> {
//            // 异步记录日志信息
//            logsService.addLogs(logs);
//        });
//    }
//    com.example.isoftservice.service
private static final Logger logger = LoggerFactory.getLogger(com.example.isoftservice.service.aop.LogsAspect.class);

    @Pointcut("execution(* com.example.isoftservice.service.*.*(..))")
    public void pointCut(){

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null){
            return;
        }
        HttpServletRequest request =attributes.getRequest();
        String ip = request.getRemoteHost();
        String username = request.getSession().getId();
        String now = new SimpleDateFormat("yyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName();
        Message message = new Message();
        message.setIp(ip);
        message.setTarget(target);
        message.setTime(now);
        message.setUser(username);
        messageMapper.insert(message);
        logger.info(String.format("用户[%s],ip:[%s],在[%s],访问了[%s].",username, ip, now, target));
    }

}


